import numpy as np
import pandas as pd
print("Hello,AI World")

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA


# 给定高维数据, 每一行代表一个样本，每一列代表一个特征（共5维）
X = np.array([
    [2.5, 2.4, 1.2, 3.5, 4.1],
    [0.5, 0.7, 0.3, 0.9, 1.1],
    [2.2, 2.9, 1.8, 3.0, 3.9],
    [1.9, 2.2, 1.5, 2.7, 3.2],
    [3.1, 3.0, 2.5, 3.8, 4.5],
    [2.3, 2.7, 1.9, 3.3, 3.8]
])

print("原始数据形状:", X.shape)

#  数据标准化

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

#  PCA降维 降到二维以便可视化
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

print("降维后数据形状:", X_pca.shape)
print("各主成分解释的方差比例:", pca.explained_variance_ratio_)
print("累计解释方差比例:", np.sum(pca.explained_variance_ratio_))

# 可视化结果
plt.figure(figsize=(6,5))
plt.scatter(X_pca[:,0], X_pca[:,1], color='blue', s=60)
for i, txt in enumerate(range(len(X_pca))):
    plt.annotate(f"样本{txt+1}", (X_pca[i,0]+0.05, X_pca[i,1]))
plt.title("PCA 降维结果 (5D → 2D)")
plt.xlabel("主成分1")
plt.ylabel("主成分2")
plt.grid(True)
plt.show()


